#!/bin/bash
# -*- coding: utf-8 -*-

import os
import time
import datetime

BASE_PATH = os.path.dirname(os.path.abspath(__file__))
INFO_FILE_PATH = os.path.join(BASE_PATH, 'info.txt')
LOG_FILE_PATH = os.path.join(BASE_PATH, 'log.log')

USER_STATUS = {
    "user_name": None,
    "login_status": None
}


def auth_wrapper(func):
    """  用户认证装饰器 """

    def inner(*args, **kwargs):
        if USER_STATUS["login_status"]:
            return func(*args, **kwargs)
        else:
            if login():
                return func(*args, **kwargs)

    return inner


def log_wrapper(func):
    """ 日志装饰器 """

    def inner(*args, **kwargs):
        t = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        content = f"用户[{USER_STATUS['user_name']}]:[{t}] 执行了[{func.__name__}]函数\n"
        print(content.strip())
        write_file(content, 'a', LOG_FILE_PATH)
        return func(*args, **kwargs)

    return inner


def login():
    """ 登录函数 """
    count = 3
    while count > 0:
        print('欢迎来登录'.center(30, '+'))
        user = input('user或输入q/Q退出登录: ').strip()
        if user.upper() == "Q":
            break
        user_dict = read_file(INFO_FILE_PATH)
        pwd = input('pwd: ')
        if user in user_dict and pwd == user_dict[user]:
            USER_STATUS['user_name'] = user
            USER_STATUS['login_status'] = True
            print(f'用户[{user}]登录成功，正在为你跳转.....')
            return True
        else:
            count -= 1
            print(f'用户名或者密码输入错误，请重新尝试， 你还有[{count}]次机会')
            cmd = input('输入y跳转到注册，任意键继续登录')
            if cmd.upper() == 'Y':
                register()
                break

    else:
        print('三次尝试机会已用尽，现已退出程序')
        time.sleep(0.001)
        my_exit()


def read_file(file_path):
    """  专门用于读取文本文件的 """
    if not os.path.exists(file_path):  # 如果文件不存在，先创建
        open(file_path, 'wb').close()
    user_dict = {}
    with open(file_path, 'r', encoding='utf8') as f:
        for line in f:
            u, p = line.strip().split(',')
            user_dict[u] = p
    return user_dict


def write_file(content, mode, file_path):
    """  专门用于写入文本文件的 """
    with open(file_path, mode=mode, encoding='utf8') as f:
        f.write(content)


def register():
    """ 注册函数 """
    while True:
        print('欢迎来注册'.center(30, '+'))
        user = input('user或输入q/Q退出注册: ').strip()
        if user.upper() == "Q":
            break
        user_dict = read_file(INFO_FILE_PATH)
        # print(1111, user_dict)
        if user in user_dict:
            print(f'用户[{user}]已存在')
            continue
        pwd = input('pwd: ')
        write_file(f"{user},{pwd}\n", 'a', INFO_FILE_PATH)
        USER_STATUS['user_name'] = user
        USER_STATUS['login_status'] = True
        print(f'用户[{user}]注册成功,且已自动登录成功, 正在为你跳转到首页')
        break


@auth_wrapper
@log_wrapper
def article():  # 多装饰器：log_wrapper(auth_wrapper(article()))
    """ 文章页面 """
    print(f'欢迎用户[{USER_STATUS["user_name"]}]访问文章页面')


@auth_wrapper
@log_wrapper
def diary():
    """ 日记页面 """
    print(f'欢迎用户[{USER_STATUS["user_name"]}]访问日记页面')


@auth_wrapper
@log_wrapper
def comment():
    """ 评论 """
    print(f'欢迎用户[{USER_STATUS["user_name"]}]访问评论页面')


@auth_wrapper
@log_wrapper
def collect():
    """ 收藏"""
    print(f'欢迎用户[{USER_STATUS["user_name"]}]访问收藏页面')


def logout():
    """  注销函数 """
    USER_STATUS['user_name'] = None
    USER_STATUS['login_status'] = None
    print(f'注销成功')


def my_exit():
    """  退出程序 """
    exit('886, 再来呦！！！')


def handler():
    """ 系统交互函数 """
    # 交互，法1
    # choice_dict = {
    #     1: login,
    #     2: register,
    # }
    # while True:
    #     print('欢迎光临博客园，请选择:\n1. 登录\n2. 注册')
    #     choice = input('请选择序号: ')
    #     if choice.isdecimal():
    #         choice = int(choice)
    #         if 1 <= choice <= 2:
    #             choice_dict[choice]()
    #         else:
    #             print('输入的需要不存在')
    #     else:
    #         print('非法输入')

    # 交互，法2
    choice_dict = {
        "1": [login, '登录'],
        "2": [register, '注册'],
        "3": [article, '文章页面'],
        "4": [diary, '日记页面'],
        "5": [comment, '评论页面'],
        "6": [collect, '收藏页面'],
        "7": [logout, '注销'],
        "8": [my_exit, '退出程序'],
    }
    while True:
        u = USER_STATUS["user_name"] if USER_STATUS['login_status'] else "游客"
        print(f'欢迎[{u}]光临博客园'.center(30, '-'))
        for k, v in choice_dict.items():
            print(k, v[-1])
        choice = input('请选择序号: ')
        if choice in choice_dict:
            choice_dict[choice][0]()
        else:
            print('非法输入')


if __name__ == '__main__':
    handler()
